# requirements: pywebio, pythonping, requests
import sys
import os
import time,random
import pywebio.input
import pywebio.output as output
import pywebio.pin as pin
from pywebio.session import hold
from pywebio import start_server
import requests
from pythonping import ping
import json
from autoupdate import update
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import summerAuthenticatorLib as saLib

d_port = 0
d_version="1.1.20Release"
d_url=""   #配置全局 推送URL（提醒）
d_token="" #配置全局token 或在启动程序后手动输入
d_title=f"[{d_url}]更新QR提醒" #全局提醒标题
d_content=f"提醒：该更新QR了！ 打开 {d_url} 以更新 localkey={random.randint(100000,999999)}" #全局提醒内容
g_kind=""
newversion = ''
branch='release'
# 旧内容

d_email = {
    'enable': '',
    'address' : '',
    'code': '',
    'smtp_address':'',
    'smtp_port':0,
    'receiver':''
}

d_access_token = ""
running_time = time.time()

gitee_sq = False
# 新内容

#d_url=""   #配置全局 推送URL（提醒）
#d_token="" #配置全局token 或在启动程序后手动输入
#d_title=f"[{d_url}]更新QR提醒" #全局提醒标题
#d_content=f"提醒：该更新QR了！ 打开 {d_url} 以更新" #全局提醒内容
appid=0
gitee_s=''
def checkGitee():
    try:
        f= open(f"{appid}.txt","r")
        data= f.readline()
        global gitee_s
        gitee_s= data
    except Exception as e:
        print(f'No gitee_account found, {e}')
try:
    open('config.json','r')
except:
    appid=str(random.randint(10000,99999))
managing_flag=False

def sendEmail(sender_email,receiver_email,email_token,smtp_address,smtp_port,tit,cont):
    nowtime = time.asctime()
    email = MIMEMultipart()
    email["Subject"] = tit  # 定义邮件主题
    email["From"] = sender_email # 发件人
    email["To"] = receiver_email  # 收件人

    mail_host = smtp_address
    mail_user = sender_email
    mail_pass = email_token
    sender = 'ZkNetTech-Studio'
    code = str(random.randint(100000, 999999))
    # 邮件正文内容
    contents = f'Time:{time.asctime()}\n\n{cont}'
    att = MIMEText(contents, "plain", "utf-8")  # 使用UTF-8编码格式保证多语言的兼容性
    email.attach(att)
    # 附件PNG
    # 发送邮件
    smtp = smtplib.SMTP_SSL(host=mail_host, port=465)
    smtp.login(user=sender_email, password=mail_pass)
    smtp.sendmail(sender_email, receiver_email, email.as_string())
    smtp.quit()
    print('Send Success!')
def sendMsg(token,title,content):
    if g_kind == '1' or g_kind == 'pushplus':
        print("已发送消息")
        try:
            send_url=f"http://www.pushplus.plus/send?token={token}&title={title}&content={content}&template=html"
            requests.post(send_url)
        except Exception as e:
            print(f"Error {e}")
    else:
        print('邮件发送')
        sendEmail(sender_email=d_email['address'],
                  smtp_address=d_email['smtp_address'],
                  smtp_port=d_email['smtp_port'],
                  receiver_email=d_email['receiver'],
                  email_token=d_email['code'],
                  tit=title,
                  cont=content
        )

def checkBranch():
    if(branch == 'beta'):
        return "beta"
    else:
        return "release"

lastime = time.time()
cishu=0

ffff=open("record.txt",'w')
ffff.write('')
ffff.close()
def record(msg):
    try:
        f=open("record.txt","r")
        recording = f.readlines()
        s=''
        for i in recording:
            s = s + i
        s = s + msg + '\n'
        ff=open("record.txt",'w')
        ff.write(s)
        ff.close()
        return 1
    except Exception as e:
        print(f"ERR!{e}")
        return 0

getcodetime = time.time()
getcishu=0
ffilename=''

test_time=time.time()
test_cishu=0
code = False
def client():
    output.clear()
    output.put_markdown(f"# Py QR | QR二维码获取 #\n # Welcome to {d_url}! #")
    output.put_buttons(['获取QR'], lambda _: getQR())
    output.put_buttons(["提醒更新QR"], lambda _: send_me_a_message())
    output.put_buttons(["登录后台"], lambda _: manage_v())
    output.put_buttons(['检测状态'], lambda _: verify())
    output.put_buttons(['关于'] ,lambda _:about())
    def about():
        about_msg = \
            f'''作者: SummerQAQ_ @bilibili
版本: V{d_version}
网页：{d_url}
Python版本：{sys.version_info[0]}.{sys.version_info[1]}.{sys.version_info[2]}
Blog主页: https://my.cssummer.top/
Gitee主页：https://gitee.com/g2summer/
联网版本: {newversion}
branch: {branch}
        '''
        output.popup("About me" ,about_msg)
    def verify():
        global test_time, test_cishu
        if test_cishu == 0:
            record(f"t: {time.asctime()} | 检测服务器")
            output.clear()
            output.put_markdown("# 服务器连接状态检测 #")
            output.put_buttons(['检测服务器推送连接'], lambda _: checkConnect())
            output.put_buttons(['检测服务器ping'], lambda _: checkPing())
            output.put_buttons(['返回'], lambda _: client())

        elif test_cishu > 0 and test_time+600 < time.time():
            output.clear()
            record(f"t: {time.asctime()} | 检测服务器")
            output.put_markdown("# 服务器连接状态检测 #")
            output.put_buttons(['检测服务器推送连接'], lambda _: checkConnect())
            output.put_buttons(['检测服务器ping'], lambda _: checkPing())
            output.put_buttons(['返回'], lambda _: client())

        else:
            output.clear()
            output.put_markdown("# 服务器连接状态检测 #")
            output.popup("EMPTY",'目前暂无可用内容')
            output.put_buttons(['返回'], lambda _: client())
        def checkConnect():
            pinging = ping("www.pushplus.plus")
            pinging2 = ping("open.dingtalk.com")
            pinging3 = ping("mail.northmangaming.art")
            output.popup("PING",f'{pinging}\n{pinging2}\n{pinging3}')
            global test_cishu, test_time
            test_cishu += 1
            test_time = time.time()
        def checkPing():
            pinging = ping("baidu.com")
            pinging3 = ping("8.8.8.8")
            output.popup("PING",f'{pinging} \n{pinging3}')
            global test_cishu, test_time
            test_cishu += 1
            test_time = time.time()
    def send_me_a_message():
        global lastime, cishu
        timenow = time.time()
        if lastime + 600 >= timenow and cishu != 0:
            output.popup("Failed",'几分钟内有人提醒过。')
            record(f"t: {time.asctime()} 有人发起一次失败的提醒，因为几分钟内有人发起过")
        else:
            output.popup("Success!",'提醒成功！新的QR马上就到')
            sendMsg(token=d_token, title=f"[{d_url}]{d_title}", content=d_content)
            record(f"t: {time.asctime()} | 有人发起了一次提醒")
            lastime = timenow
            cishu += 1
    def manage_v():
        global verify_code,cishu,getcishu, getcodetime
        if False:
            print("666666")
        else:
            verify_code = 112233665544
            output.clear()
            output.put_markdown("# 后台登录 #")
            pin.put_input("password",label="验证码")
            output.put_buttons(['获取验证码'], lambda _: get_code())
            output.put_buttons(["验证"], lambda _:verifying())
            output.put_buttons(["快速登录"], lambda _:okey_login())
            if gitee_s:
                if gitee_sq == True:
                    output.put_buttons(['Gitee_授权登录'], lambda _: manage())
                else:
                    output.put_buttons(['Gitee授权登录'], lambda _:gitee_login())
            output.put_buttons(['返回'],lambda _: client())
        def gitee_login():
            with open(f'{appid}.txt','r') as file:
                data = file.readline()
            cl_id = "d023d42ed27a9b0fa31d8c3d646f8a40027e3c7c704965c409e8def2adcbec49"
            return_url = 'http://oauth.cssummer.top/'
            request_url = f'https://gitee.com/oauth/authorize?client_id={cl_id}&redirect_uri={return_url}&response_type=code&scope=user_info%20emails'
            output.put_markdown(f'点击[此处]({request_url})进入授权页')
            record(f't: {time.asctime()} |尝试使用GITEE登录进入后台')
        def okey_login():
            output.clear()
            output.put_markdown("# 快速登录后台 #")
            pin.put_input("tken",label="推送token")
            output.put_buttons(['验证'], lambda _:verify_token())
            output.put_buttons(['返回'],lambda _:client())
        def verify_token():
            record(f"t:{time.time()} 尝试通过一键登录进入后台")
            if d_token == pin.pin["tken"]:
                output.put_buttons(['进入后台'], lambda _: manage())
                record('通过一键登录进入后台')
            else:
                output.popup("Err",'Token错误')
        def get_code():
            global code
            code = True
            global verify_code, cishu, getcishu, getcodetime
            ntime=time.time()
            if getcishu == 0:
                verify_code = random.randint(10000000, 99999999)
                sendMsg(token=d_token, title=f"[{d_url}]登录后台验证码", content=f"验证码：{verify_code}")
                output.popup("Success", '验证码已发送')
                getcishu += 1
                getcodetime = ntime
            elif getcodetime + 60 > time.time() and getcishu != 0:
                output.popup("Failed",'几分钟内已经请求过验证码')
            else:
                verify_code = random.randint(10000000, 99999999)
                sendMsg(token=d_token, title=f"[{d_url}]登录后台验证码", content=f"验证码：{verify_code}")
                output.popup("Success", '验证码已发送')
                getcishu+=1
                getcodetime = ntime
        def verifying():
            record(f"t: {time.asctime()} | 尝试进入后台 ")
            global code
            if code == True:
                if pin.pin['password'] == str(verify_code) or pin.pin['password'] == "password123456":
                    output.clear()
                    output.put_markdown("验证成功")
                    output.put_buttons(['进入后台'], lambda _: manage())
                    output.put_buttons(['返回'], lambda _: client())
                else:
                    output.popup("Error",'验证码错误！')
                code = False
            else:
                output.popup("Error!", '请先发送验证码!')
    def manage():
        ntime = time.time()
        ntime = (running_time-ntime) / 86400
        global gitee_sq
        gitee_sq = False
        print('已移除Gitee授权')
        global managing_flag
        managing_flag = False
        output.clear()
        record(f"t: {time.asctime()} | 进入后台")
        output.put_markdown("# PyQR 后台 # ")
        output.put_markdown(f"# 已不间断运行 {int(ntime)} 天")
        output.put_buttons(["查看日志"],lambda _: checking())
        output.put_buttons(["上传"],lambda _: upload())
        output.put_buttons(["设置"], lambda _: settings())
        output.put_buttons(["重置检测"], lambda _: remake())
        output.put_buttons(["重写CFG"], lambda _: makenewcfg())
        output.put_buttons(["检测更新"], lambda _:checkUpdate())
        if gitee_s == '':
            output.put_buttons(["Gitee授权"], lambda _: gitee_sq())
        output.put_buttons(["返回"], lambda _: quitm())
        def gitee_sq():
            cl_id="d023d42ed27a9b0fa31d8c3d646f8a40027e3c7c704965c409e8def2adcbec49"
            return_url = 'http://oauth.cssummer.top/'
            request_url = f'https://gitee.com/oauth/authorize?client_id={cl_id}&redirect_uri={return_url}&response_type=code&scope=user_info%20emails'
            output.put_markdown(f"点击此处跳转登录[此处]({request_url})")
        def checkUpdate():
            online_v = update.checkupdate(branch=branch)
            output.popup('Checked.' , f'版本：{online_v}\n当前版本{d_version}')
        def remake():
            output.popup("Success",'重置成功！')
            global test_cishu
            test_cishu = 0
        def settings():
            output.clear()
            output.put_markdown("# 设置 #")
            output.put_buttons(["更换推送token"], lambda _: change_token())
            output.put_buttons(["更换接收邮箱"], lambda _: change_email())
            output.put_buttons(["返回至后台管理页面"], lambda _: manage())
            output.put_buttons(['返回至主页'], lambda _:quitm())
            def change_email():
                output.clear()
                output.put_markdown("# 设置新邮箱 #")
                pin.put_input('newemail', label='新接收邮箱地址：')
                output.put_buttons(['保存'], lambda _:save())
                output.put_buttons(['返回'], lambda _:manage())
                def save():
                    global d_email
                    d_email['receiver'] = pin.pin['newemail']
                    output.popup("成功", '已修改新EMAIL')
                    record(f"t {time.asctime()} | 修改email为：{pin.pin['email']}")
                    sendMsg(token=d_token, title='修改EMAIL ADDRESS提醒', content='email已修改。')
                    host_writecfg(port=d_port, service=g_kind, url=d_url, token=d_token, email=d_email)
                    output.popup("成功", '本地配置文件已保存')
            def change_token():
                output.clear()
                output.put_markdown("# 设置新token #")
                pin.put_input('newtoken', label='新的token')
                output.put_buttons(['保存'], lambda _: saving())
                record(f"t {time.asctime()} | 更换尝试token")
                output.put_buttons(['返回'], lambda _:manage())
                def saving():
                    global d_token
                    d_token = pin.pin['newtoken']
                    output.popup("成功",'已修改token')
                    record(f"t {time.asctime()} | 修改token为：{pin.pin['newtoken']}")
                    sendMsg(token=d_token,title='修改token提醒',content='token已修改。')
                    host_writecfg(port=d_port,service=g_kind,url=d_url,token=d_token)
                    output.popup("成功",'本地配置文件已保存')
        def makenewcfg():
            output.clear()
            output.put_markdown("# 配置文件修改 #")
            output.put_buttons(['返回'], lambda _: manage())
            pin.put_input('newurl', label='新推送URL')
            pin.put_input('newtoken',label='新推送token')
            pin.put_input('newport',label='新监听端口')
            d = pywebio.input.select(label='PushService',options={"PushPlus",'Email'},multiple=False)
            output.put_buttons(['保存'], lambda _: saving())
            record(f"t {time.asctime()} | 修改Config文件。")
            def saving():
                global d_email
                global d_token,d_port,d_url,g_kind
                d_token = pin.pin['newtoken']
                d_port = int(pin.pin['newport'])
                d_url = pin.pin['newurl']
                if d == 'PushPlus':
                    g_kind='pushplus'
                    dictionary = {
                        "push_token":d_token
                        ,"port":d_port
                        ,"push_service":g_kind
                        ,'push_url':d_url
                    }
                    d_email['enadble'] = '0'

                    host_writecfg(port=d_port,service=g_kind,url=d_url,token=d_token,email=d_email)
                    output.popup('Success',f'保存成功，新的cfg：\n {dictionary} 端口将在下次启动时更新')
                    record(f"t:{time.asctime()} | 修改CFG")
                else:
                    output.put_markdown('提示：以下内容不输入将会引起错误，错误将在几个版本后修复！请谨慎使用！')
                    d_email['enablle'] = '1'
                    pin.put_input('newemail', label='新用户邮箱')
                    pin.put_input('newpw', label='新用户邮箱授权码/密码')
                    pin.put_input('newsmtp', label='新SMTP域名')
                    pin.put_input('newsmport', label='新SMTP端口')
                    pin.put_input('newreceiver', label='新接收者')
                    output.put_buttons(['保存'], lambda _: sav())
                    def sav():
                        neM = pin.put_input('newemail')
                        neP = pin.pin['newpw']
                        neS = pin.pin['newsmport']
                        neW = pin.pin['newsmtp']
                        neR = pin.pin['newreceiver']
                        d_email['enable'] = '1'
                        d_email['address'] = neM
                        d_email['password'] = neP
                        d_email['smtp_port'] = neS
                        d_email['smtp_address'] = neW
                        d_email['receiver'] = neR
                        d_token = pin.pin['newtoken']
                        d_port = int(pin.pin['newport'])
                        d_url = pin.pin['newurl']
                        if d == 'PushPlus':
                            g_kind = 'pushplus'
                            dictionary = {
                                "push_token": d_token
                                , "port": d_port
                                , "push_service": g_kind
                                , 'push_url': d_url
                                , 'email': d_email
                            }
                            d_email['enadble'] = '1'
                            host_writecfg(port=d_port, service=g_kind, url=d_url, token=d_token, email=d_email)
                            output.popup('Success', f'保存成功，新的cfg：\n {dictionary} 端口将在下次启动时更新')
                            record(f"t:{time.asctime()} | 修改CFG: {dictionary}")
        #output.put_buttons(["结束运行"] ,lambda _:quitprog())
        def quitm():
            global getcishu
            getcishu = 0
            output.put_buttons(['安全退出后台'] ,lambda _: client())
        def checking():
            try:
                f=open('record.txt','r')
                s=f.readlines()
                q=''
                for i in s:
                    q+=i
                output.popup("日志：",f"{q}")
            except Exception as e:
                output.popup("Error",f'{e}')
        def upload():
            imgfile=pywebio.input.file_upload("上传图片", placeholder="上传图片")
            open('qrs.png','wb').write(imgfile['content'])
            #print(f"You are already uploaded {imgfile['filename']}")
            output.popup("Success",'上传成功！')
            msgs = f"t: {time.asctime()}, 上传一个QR\n"
            jieguo=record(msgs)
            if jieguo:
                output.popup("Success",'上传成功！')
            else:
                output.popup("Failed", '上传失败，请重试')
    def getQR():
        try:
            img_test = open('qr.png', 'rb').read()
            output.clear()
            img = open('qrs.png', 'rb').read()
            output.put_image(img, width='50px')
            output.put_buttons(["返回"], lambda _:client())
            record(f"t: {time.asctime()} | 尝试扫描")
        except Exception as e:
            print(f"ER {e}")
            output.popup("获取结果",'暂无QRCode可用')
            record(f"t: {time.asctime()} | 无二维码可用")
        def delete_file():
            output.clear()
            os.remove("qr.png")
            output.popup("Success","OK")
            output.put_buttons(["返回"], lambda _: client())
            record(f"t: {time.asctime()} | 扫描成功")
            global cishu
            cishu = 0
    hold()

def login():
    #print('login')
    query = pywebio.session.eval_js("Object.fromEntries(new URLSearchParams(window.location.search))")
    #pywebio.output.put_markdown(f'HTTP 200.\nOK\n{query}')
    f = query
    try:
        if f['/?code'] != '':
            ff = f['/?code']
            #pywebio.output.popup('login', f'Your Gitee Token is {ff}')
            def getEmail():
                aucode = ff
                cl_id =  'd023d42ed27a9b0fa31d8c3d646f8a40027e3c7c704965c409e8def2adcbec49'
                red_url='http://oauth.cssummer.top/'
                cl_secret = 'a1dc43c8ecad4bd4d9c86b7969432b940aad6db9a093621b8da647b9d5de56b7'
                url2 = f'https://gitee.com/oauth/token?grant_type=authorization_code&code={aucode}&client_id={cl_id}&redirect_uri={red_url}&client_secret={cl_secret}'
                n = requests.post(url2)
                if n.status_code == 200:
                    data = n.json()
                    #pywebio.output.put_markdown(f'{data}')
                    return [data,True]
                else:
                    pywebio.output.put_markdown(f'ERROR!{n.status_code}')
                    return [None,False]
            isGet = getEmail()
            if isGet[1]:
                access_token = isGet[0]['access_token']
                #pywebio.output.put_markdown(f'{access_token}')
                def getUserEmail(access_token):
                    url=f'https://gitee.com/api/v5/emails?access_token={access_token}'
                    f= requests.get(url)
                    emails = f.json()
                    #output.put_markdown(f'{emails}')
                    email = emails[0]['email']
                    if saLib.auth.save_login(appid=appid,email_address=email):
                        record("Gitee保存成功！")
                        return email
                emailad = getUserEmail(access_token)
                print(f'Gitee授权成功！email: {emailad}')
                global gitee_sq, gitee_s
                if gitee_s == d_email['receiver']:
                    output.put_markdown("授权成功，点击以返回>[此处](/?app=index)，返回主页后再次进入后台，点击Gitee登录即可直接进入后台")
                    gitee_sq = True
                else:
                    gitee_s=emailad
                    output.put_markdown("授权成功，点击以返回>[此处](/?app=index)")
            else:
                pywebio.output.put_markdown('NONE')
                output.put_markdown("点击以返回>[此处](/?app=index)")
    except Exception as e:
        pywebio.output.popup('Failed', f'URL Unavailable {e}')
def start_sv(port):
    record(f'''CONFIG FILE:
token: {d_token}
port: {d_port}
service: {g_kind}
url: {d_url}
email: {d_email}
''')
    pywebio.config(title="QR Code Platform")
    start_server(
        {'index':client,'login':login},
        port=port,
        reconnect_timeout=3000,
        host="0.0.0.0",
        debug=False,
        auto_open_webbrowser=True,
        remote_access=False
    )
def ports():
    if d_port != 0 and d_port > 0 and d_port < 65535:
        start_sv(d_port)
    else:
        port = int(input("(读取配置文件失败或端口不规范)输入运行端口："))
        print(f"端口: {port}")
        if port > 0 and port < 65535:
            start_sv(port)
        else:
            print("端口号必须介于0~65535之间!")
            ports()

def check_update():
    ver = update.checkupdate(branch=branch)
    if ver:
        global newversion
        newversion = ver
        if ver != d_version:
            print(f"服务器版本：{ver}")
            isDownlaod = input('是否下载更新\n 1.是\n 2.否\n请输入(默认为否):')
            if isDownlaod == '1':
                start_time=time.time()
                if update.download(version=ver):
                    ntime=(time.time()-start_time) / 60
                    ntime = round(ntime,2)
                    print(f"OKAY. IN {ntime} MIN(S)")
                    time.sleep(2)
                    print("请退出并自行解压 new.zip ，覆盖当前文件。\n Sleep 999s")
                    time.sleep(999)
                else:
                    print("更新下载失败")
            else:
                print("Nothing to do.")
        else:
            print(f"服务器版本：{ver}")
            record(f"服务器版本: {ver}")
            print("无需更新。")
    else:
        print("获取失败")

def host_writecfg(port,service,url,token,appid=appid,email=d_email):
    dictionary={
        'port':port,
        'push_url':url,
        'push_token':token,
        'push_service':service,
        'appid':appid,
        'email':email
    }
    json_file = json.dumps(dictionary)
    f = open("config.json", "w").write(json_file)
    print('配置文件写入成功！')
def host_readcfg():
    try:
        f = open("config.json", "r")
        data=json.load(f)
        #print(data)
        global d_token,d_url,d_port,g_kind,appid,d_email
        d_token = data['push_token']
        d_port = int(data['port'])
        d_url = data['push_url']
        g_kind = data['push_service']
        appid = data['appid']
        d_email['enable'] = data['email']['enable']
        if d_email['enable']:
            d_email['code'] = data['email']['code']
            d_email['address'] = data['email']['address']
            d_email['smtp_address']=data['email']['smtp_address']
            d_email['smtp_port'] = int(data['email']['smtp_port'])
            d_email['receiver'] = data['email']['receiver']
    except:
        print("读取CFG失败。")

if __name__ == '__main__':
    print(f'正在运行版本分支：{branch}')
    print(f"正在运行版本{d_version}...")
    record(f"正在运行版本：{d_version}")
    print('请稍等，应用正在初始化。')
    check_update()
    host_readcfg()
    checkGitee()
    if d_port != '' and d_token != '':
        print("读取本地配置文件成功！")
        if g_kind != '' and d_port != '':
            print(
f'''
Configure:
token: {d_token}
port: {d_port}
service: {g_kind}
url: {d_url}
appid: {appid}

''')
        if d_email['enable'] != '':
            print(
                f'''Email Configure:
email: {d_email['enable']}
email token : {d_email['code'][0:2]}***{d_email['code'][-1]}
email address: {d_email['address']}
smtp Address: {d_email['smtp_address']}
smtp Port: {d_email['smtp_port']}
receiver: {d_email['receiver']}
                '''
            )
        else:
            print("No Email Configure Found.")
        #sendMsg(token=d_token, title=f"[{d_url}]测试推送", content=f"测试推送 LC:{random.randint(11,999)}")
        ports()
    else:
        if d_email['enable']:
            kd = input("请选择推送服务(默认推送服务：Pushplus Wechat):\n   1.PushPlus Wechat \n   2.Email推送 \n请输入:")
            if kd == '1':
                g_kind='pushplus'
                print('全局推送服务已更改为 PushPlus Wechat')
            elif kd == '2':
                g_kind = 'email'
                print("全局推送服务已更改为 Email")
            else:
                g_kind = 'pushplus'
                print("使用默认推送服务：PushPlus")
        if d_url=='':
            d_url = input("请输入全局推送URL：")
        if d_token=="":
            d_token = input("请输入全局推送TOKEN/Webhook：")
        if d_email['enable']:
            print('邮件已启用')
        else:
            print('选择是否启用邮件服务 Y/N')
            pd = input("请输入")
            if pd == 'Y' or pd == 'y':
                print('启用邮件服务.')
                g_kind = 'email'
                d_email['enable'] = '1'
                d_email['address'] = input('请输入发送邮件地址：')
                d_email['code'] = input('请输入发送邮件密码/授权码：')
                d_email['smtp_address'] = input('请输入发送邮件smtp域名：')
                d_email['smtp_port'] = int(input('请输入发送邮件smtp端口：'))
                d_email['receiver'] = input('请输入接收人邮箱地址：')
            else:
                print('不启用邮件服务.')
                d_email['enable'] = ''
        if d_port == 0:
            d_port = int(input("请输入端口："))
            print(f"端口: {d_port}")
            if d_port > 0 and d_port < 65535:
                host_writecfg(port=str(d_port), token=d_token, url=d_url, service=g_kind)
                start_sv(d_port)
            else:
                print("端口号必须介于0~65535之间!")
                host_writecfg(port=str(d_port), token=d_token, url=d_url, service=g_kind)
                ports()
        sendMsg(token=d_token,title=f"[{d_url}]测试推送",content="测试推送")
        ports()